package com.hsmw.schedule.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.hsmw.common.base.BaseService;
import com.hsmw.schedule.mapper.HsmwCorporationCompanyMapper;
import com.hsmw.schedule.mapper.HsmwOrderMapper;
import com.hsmw.schedule.mapper.HsmwUserDriverMapper;
import com.htn.common.core.constant.*;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author WD
 */
@Slf4j
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwOrderService extends BaseService<HsmwOrderMapper, HsmwOrder> {

    @Autowired
    private HsmwOrderMapper hsmwOrderMapper;
    @Autowired
    private HsmwOrderForceManRelationService hsmwOrderForceManRelationService;
    @Autowired
    private HsmwOrderVehicleRelationService hsmwOrderVehicleRelationService;
    @Autowired
    private HsmwOrderVehicleRequestService hsmwOrderVehicleRequestService;

    @Autowired
    private HsmwVehicleService hsmwVehicleService;

    @Autowired
    private HsmwUserDriverMapper hsmwUserDriverMapper;

    @Autowired
    private HsmwReportService hsmwReportService;

    @Autowired
    private HsmwOrderService hsmwOrderService;

    @Autowired
    private HsmwCorporationCompanyMapper hsmwCorporationCompanyMapper;

    @Value(value = "${sms.appKey}")
    private String appKey;
    @Value(value = "${sms.channel}")
    private String channel;
    @Value(value = "${sms.smsSign}")
    private String smsSign;
    @Value(value = "${sms.appId}")
    private int appId;
    @Value(value = "${sms.orderTemplateId}")
    private int orderTemplateId;

    @Value(value = "${sms.driverTemplateId}")
    private int driverTemplateId;

    @Value(value = "${sms.orderTimeoutNoticeBiz}")
    private int orderTimeoutNoticeBiz;

    @Value(value = "${sms.textOrderTimeOut}")
    private int textOrderTimeOut;

    @Value(value = "${sms.newConcreteOrder}")
    private int newConcreteOrder;

    @Value(value = "${sms.htnUpdateTime}")
    private int htnUpdateTime;


    @Value(value = "${sms.foremanCreateOrderSms}")
    private int foremanCreateOrderSms;


    @Value(value = "${sms.projectManCreateOrderSms}")
    private int projectManCreateOrderSms;

    @Value(value = "${sms.driverOrderCanceled}")
    private int driverOrderCanceled;


    @Value(value = "${sms.driverOrderUnArrivedCanceled}")
    private int driverOrderUnArrivedCanceled;


    final static String voiceCode = "0e7fe15a-5f6a-412f-8172-9f324d8c3bce.wav";

    final static Long queryTime = 3L;

    static {
        System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2,SSLv3");
    }



    public HsmwOrderVO getHsmwOrderById(String id) {
        HsmwOrderVO hsmwOrderVO = new HsmwOrderVO();
        BeanUtil.copyProperties(hsmwOrderMapper.selectById(id), hsmwOrderVO);
        List<HsmwOrderForceManRelation> hsmwOrderForceManRelationList = hsmwOrderForceManRelationService.list(Wrappers.lambdaQuery(HsmwOrderForceManRelation.class).eq(HsmwOrderForceManRelation::getOrderId, id));
        //hsmwOrderVO.setForceManRelations(hsmwOrderForceManRelationList);
        List<HsmwOrderVehicleRequest> hsmwOrderVehicleRequestList = hsmwOrderVehicleRequestService.list(Wrappers.lambdaQuery(HsmwOrderVehicleRequest.class).eq(HsmwOrderVehicleRequest::getOrderId, id));
        hsmwOrderVO.setVehicleRequestList(hsmwOrderVehicleRequestList);
        List<HsmwOrderVehicleRelation> vehicleRelationList = hsmwOrderVehicleRelationService.list(new LambdaQueryWrapper<HsmwOrderVehicleRelation>().eq(HsmwOrderVehicleRelation::getOrderId, id));
        hsmwOrderVO.setVehicleRelationList(vehicleRelationList);
        return hsmwOrderVO;
    }

    //通过需求ID 获取符合该需求的车辆信息 自营 合作 平台 三种类型
    public List<HsmwVehicle> getVehicleListByRequestId(HsmwOrderVehicleRequest hsmwOrderVehicleRequest,String type,HsmwHtnUser createuser,String itemCreateUserCompanyId,HsmwHtnUser itemCreator) {
        LambdaQueryWrapper<HsmwVehicle> lambdaQueryWrapper = Wrappers.lambdaQuery(HsmwVehicle.class);
        List<HsmwVehicle> avaliableVehicles = new ArrayList<>(128);
        if(hsmwOrderVehicleRequest.isFlag()){
            lambdaQueryWrapper.ne(HsmwVehicle::getVehicleModel, hsmwOrderVehicleRequest.getVehicleModel());
        }else {
            lambdaQueryWrapper.eq(HsmwVehicle::getVehicleModel, hsmwOrderVehicleRequest.getVehicleModel());
            lambdaQueryWrapper.eq(HsmwVehicle::getVehicleType, hsmwOrderVehicleRequest.getVehicleType());
        }
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        //如果选择的桥数 不为空 则 在选择车的时候过滤一下。
        List<String> axisList = new ArrayList<>();
        if (StringUtils.isNotBlank(hsmwOrderVehicleRequest.getAxis())) {
            String axis = hsmwOrderVehicleRequest.getAxis();
            String[] axiss =axis.split(",");
            if(axiss.length>0){
                for(String ax:axiss){
                    axisList.add(ax);
                }
            }
            lambdaQueryWrapper.in(HsmwVehicle::getAxis, axisList);
        }
        //如果选择的臂节数 不为空 则 在选择车的时候过滤一下。
        List<String> segList = new ArrayList<>();
        if (StringUtils.isNotBlank(hsmwOrderVehicleRequest.getArmSegment())) {
            String segs = hsmwOrderVehicleRequest.getArmSegment();
            String[] segss =segs.split(",");
            if(segss.length>0){
                for(String ax:segss){
                    segList.add(ax);
                }
            }
            lambdaQueryWrapper.in(HsmwVehicle::getArmSegment, segList);
        }
        List<String> vehicleStatus = new ArrayList<>();
        vehicleStatus.add(CommonConstants.VEHICLE_FREE);
        lambdaQueryWrapper.in(HsmwVehicle::getWorkStatus, vehicleStatus);
        //首先查询出来符合的车辆
        List<HsmwVehicle> hsmwVehicleList=new ArrayList<>();
        //如果是自营的车辆列表那么
        if(CorperateTypeEnum.SELFRUN.getValue().equals(type)){
            lambdaQueryWrapper.eq(HsmwVehicle::getLeasingCompanyId,hsmwOrderVehicleRequest.getLeasingCompanyId());
            hsmwVehicleList = hsmwVehicleService.list(lambdaQueryWrapper);
        }
        if(CorperateTypeEnum.ALL.getValue().equals(type)){
            hsmwVehicleList = hsmwVehicleService.list(lambdaQueryWrapper);
        }
        if(CorperateTypeEnum.CORPERATE.getValue().equals(type)){
            LambdaQueryWrapper<HsmwCorporationCompany> lambdaQueryWrapper1= new LambdaQueryWrapper<HsmwCorporationCompany>();
            if(HtnUserTypeEnum.COMPANY.getValue().equals(createuser.getType())){
                lambdaQueryWrapper1.eq(HsmwCorporationCompany::getCompanyId,createuser.getOwnCompanyId());
            }
            if(HtnUserTypeEnum.CONCRETE.getValue().equals(createuser.getType())){
                lambdaQueryWrapper1.eq(HsmwCorporationCompany::getConcretePlantId,createuser.getOwnCompanyId());
            }
            if(HtnUserTypeEnum.FOREMAN.getValue().equals(createuser.getType())){
                if(HtnUserTypeEnum.COMPANY.getValue().equals(itemCreator.getType())){
                    lambdaQueryWrapper1.eq(HsmwCorporationCompany::getCompanyId,itemCreator.getOwnCompanyId());
                }
                if(HtnUserTypeEnum.CONCRETE.getValue().equals(itemCreator.getType())){
                    lambdaQueryWrapper1.eq(HsmwCorporationCompany::getConcretePlantId,itemCreator.getOwnCompanyId());
                }
            }
            lambdaQueryWrapper1.eq(HsmwCorporationCompany::getCorperateType,CorperateTypeEnum.CORPERATE.getValue());
            List<HsmwCorporationCompany> corporationCompanies = hsmwCorporationCompanyMapper.selectList(lambdaQueryWrapper1);
            if(CollectionUtil.isNotEmpty(corporationCompanies)){
                Set<String> companyIds  =new HashSet<>();
                companyIds  = corporationCompanies.stream().map(HsmwCorporationCompany::getCorperateCompanyId).collect(Collectors.toSet());
                lambdaQueryWrapper.in(HsmwVehicle::getLeasingCompanyId,companyIds);
            }
            //当合作公司的车辆不为空的时候 才会查询合作公司的车辆
            if(CollectionUtil.isNotEmpty(corporationCompanies)){
                hsmwVehicleList = hsmwVehicleService.list(lambdaQueryWrapper);
            }
        }
        if(!CorperateTypeEnum.CORPERATE.getValue().equals(type) && !CorperateTypeEnum.SELFRUN.getValue().equals(type) && !CorperateTypeEnum.ALL.getValue().equals(type)){
            HashMap param =  new HashMap();
            if(HtnUserTypeEnum.FOREMAN.getValue().equals(createuser.getType())){
                param.put("companyId",itemCreator.getOwnCompanyId());
            }else {
                param.put("companyId",createuser.getOwnCompanyId());
            }
            if(StringUtils.isNotBlank(hsmwOrderVehicleRequest.getVehicleType())){
                param.put("vehicleType",hsmwOrderVehicleRequest.getVehicleType());
            }
            if(StringUtils.isNotBlank(hsmwOrderVehicleRequest.getVehicleModel())){
                param.put("vehicleModel",hsmwOrderVehicleRequest.getVehicleModel());
            }
            if(CollectionUtil.isNotEmpty(segList)){
                param.put("segList",segList);
            }
            if(CollectionUtil.isNotEmpty(axisList)){
                param.put("axisList",axisList);
            }
            hsmwVehicleList=hsmwVehicleService.selectPlateformVehicles(param);
        }
        //首先查询出来符合的车辆

        HsmwOrder order = hsmwOrderService.getHsmwOrderById(hsmwOrderVehicleRequest.getOrderId());
        //判断车辆年限
        if(CollectionUtil.isNotEmpty(hsmwVehicleList) && StringUtils.isNotBlank(hsmwOrderVehicleRequest.getYears()) ){
            Iterator<HsmwVehicle> iterator = hsmwVehicleList.iterator();
            while (iterator.hasNext()) {
                HsmwVehicle hsmwVehicle = iterator.next();
                LocalDate beginDate = hsmwVehicle.getBeginTime();
                if(StringUtils.isNull(beginDate)){
                    beginDate=LocalDate.now().minusMonths(12);
                }
                long year = beginDate.until(LocalDateTime.now(), ChronoUnit.YEARS);
                long month = beginDate.until(LocalDateTime.now(), ChronoUnit.MONTHS);
                double years = month/12.0;
                String yearStr =order.getYears();
                boolean isFitable= false;
                if(StringUtils.isNotBlank(yearStr)){
                    String[] yearSub = yearStr.split(",");
                    if(yearSub.length>0){
                        for(String str :yearSub){
                            double[] between =  getYearBetween(str);
                            double begin = between[0];
                            double end = between[1];
                            if(years<=end && years>begin){
                                isFitable=true;
                                break;
                            }
                        }
                    }
                }
                if(!isFitable){
                    iterator.remove();
                }
            }
        }
        Set<String> appointVehicleIdSet = hsmwVehicleList.stream().map(HsmwVehicle::getId).collect(Collectors.toSet());
        if (CollectionUtil.isNotEmpty(appointVehicleIdSet)) {
            List<String> status = new ArrayList<>();
            status.add(CommonConstants.DRIVER_ACCEPT_ORDER);
            Map<String, List<HsmwUserDriver>> vehicleDriverMap = hsmwUserDriverMapper.selectList(Wrappers.lambdaQuery(HsmwUserDriver.class)
                    .in(HsmwUserDriver::getVehicleId, appointVehicleIdSet).in(HsmwUserDriver::getWorkStatus, status))
                    .stream()
                    .peek(System.out::println)
                    .collect(Collectors.groupingBy(HsmwUserDriver::getVehicleId));
            Iterator<HsmwVehicle> iterator1 = hsmwVehicleList.iterator();
            while (iterator1.hasNext()) {
                HsmwVehicle hsmwVehicle = iterator1.next();
                HashMap param = new HashMap();
                param.put("vehicleId", hsmwVehicle.getId());
                param.put("reachTime", dtf.format(hsmwOrderVehicleRequest.getReachTime()));
                if (CollectionUtil.isEmpty(vehicleDriverMap.get(hsmwVehicle.getId()))) {
                    iterator1.remove();
                } else if (hsmwReportService.checkIfHasleavingRecord(param)) {
                    iterator1.remove();
                }
            }
            avaliableVehicles.addAll(hsmwVehicleList);
        }
        return avaliableVehicles;
    }




    double[] getYearBetween(String  value){
        if(value.equals(VehicleYearsEnum.YEAR_0_3.getValue())){
            String name = VehicleYearsEnum.YEAR_0_3.getName();
            String[] names = name.split(",");
            return  new double[]{Double.valueOf(names[0]),Double.valueOf(names[1])};
        }
        if(value.equals(VehicleYearsEnum.YEAR_3_5.getValue())){
            String name = VehicleYearsEnum.YEAR_3_5.getName();
            String[] names = name.split(",");
            return  new double[]{Double.valueOf(names[0]),Double.valueOf(names[1])};
        }
        if(value.equals(VehicleYearsEnum.YEAR_5_7.getValue())){
            String name = VehicleYearsEnum.YEAR_5_7.getName();
            String[] names = name.split(",");
            return  new double[]{Double.valueOf(names[0]),Double.valueOf(names[1])};
        }
        if(value.equals(VehicleYearsEnum.YEAR_7_10.getValue())){
            String name = VehicleYearsEnum.YEAR_7_10.getName();
            String[] names = name.split(",");
            return  new double[]{Double.valueOf(names[0]),Double.valueOf(names[1])};
        }
        return  new double[]{10,15};

    }



    public List<HsmwOrder> expireConcreteOrders() {
        return hsmwOrderMapper.expireConcreteOrders();
    }



}
